<template>
  <view class="h-screen flex flex-col bg-[#fbfcfd]">
    <!-- 顶部标题栏 -->
    <view class="relative z-10 h-90rpx flex flex-shrink-0 items-center justify-between bg-white pt-60rpx">
      <view class="ml-20rpx h-60rpx w-60rpx flex items-center justify-center" @tap="goBack">
        <image src="https://ceshiweb.picaime.com/static/images/cart/back.png" class="h-36rpx w-36rpx" mode="aspectFit" />
      </view>
      <view class="pointer-events-none absolute left-0 right-0 flex items-center justify-center">
        <text class="text-36rpx text-black font-bold leading-[49.4rpx] tracking-0">
          选择买家
        </text>
      </view>
      <view class="mr-20rpx h-60rpx w-60rpx flex items-center justify-center">
        <!-- 占位 -->
      </view>
    </view>

    <!-- 中间分割线 -->
    <view class="h-2rpx w-full bg-[rgba(245,245,245,1)]" />

    <!-- 搜索栏 -->
    <view class="flex items-center bg-white px-30rpx py-20rpx space-x-20rpx">
      <view class="h-78rpx w-568rpx flex items-center rounded-12rpx bg-[rgba(245,246,249,1)] px-30rpx">
        <input
          v-model="searchKeyword" class="flex-1 text-28rpx text-[#333]"
          placeholder="请输入要搜索或新增的买家名称" placeholder-class="text-[#999]" @input="onSearchInput"
        >
      </view>
      <view
        class="h-72rpx w-128rpx flex items-center justify-center rounded-12rpx bg-[rgba(67,207,124,1)]"
        @tap="onSearchConfirm"
      >
        <text class="text-28rpx text-white font-medium">
          {{ isLoading ? '搜索中...' : '确认' }}
        </text>
      </view>
    </view>

    <!-- 主要内容区域 -->
    <view class="flex flex-1 overflow-hidden">
      <!-- 买家列表 -->
      <scroll-view scroll-y class="flex-1" :scroll-into-view="scrollIntoId" scroll-with-animation>
        <view class="px-30rpx py-20rpx">
          <!-- 加载状态显示 -->
          <view v-if="isLoading" class="w-full flex justify-center py-30rpx">
            <text class="text-28rpx text-[#999]">
              加载中...
            </text>
          </view>
          <!-- 无数据提示 -->
          <view v-else-if="filteredBuyerList.length === 0" class="w-full flex justify-center py-30rpx">
            <text class="text-28rpx text-[#999]">
              暂无相关买家数据
            </text>
          </view>
          <!-- 卡片模式显示买家列表 -->
          <view
            v-for="buyer in filteredBuyerList" v-else :key="buyer.id"
            class="card-item mb-20rpx h-124rpx w-600rpx flex items-center rounded-20rpx bg-white px-20rpx shadow-md"
            @tap="selectBuyer(buyer)"
          >
            <view
              class="mr-20rpx h-100rpx w-100rpx flex items-center justify-center overflow-hidden rounded-full"
            >
              <text
                v-if="!buyer.avatar"
                class="h-full w-full flex items-center justify-center bg-[#c695f1] text-48rpx text-white"
              >
                {{
                  buyer.name.charAt(0)
                }}
              </text>
              <image v-else :src="buyer.avatar" mode="aspectFill" class="h-full w-full" />
            </view>
            <view class="flex-1">
              <view class="text-32rpx text-[#333] font-medium">
                {{ buyer.name }}
              </view>
              <view v-if="buyer.phone" class="mt-6rpx text-26rpx text-[#999]">
                {{ buyer.phone }}
              </view>
            </view>
          </view>
        </view>
      </scroll-view>
      <!-- 字母索引栏 -->
      <view
        class="h-[80vh] w-80rpx flex flex-col items-center justify-center overflow-y-auto rounded-20rpx bg-white"
      >
        <view
          class="letter-index mb-10rpx h-60rpx w-full flex items-center justify-center"
          :class="{ 'active-letter': currentLetter === '全' }" @tap="onLetterClick('全')"
          @longpress="onLetterLongPress('全')"
        >
          <text
            class="text-32rpx font-normal leading-[80rpx] tracking-0"
            :class="{ 'text-[#43CF7C] font-bold': currentLetter === '全', 'text-black': currentLetter !== '全' }"
          >
            全
          </text>
        </view>
        <view
          v-for="letter in indexLetters" :key="letter"
          class="letter-index h-80rpx w-full flex items-center justify-center" :class="{ 'active-letter': currentLetter === letter }"
          @tap="onLetterClick(letter)" @longpress="onLetterLongPress(letter)"
        >
          <text
            class="text-32rpx font-normal leading-[80rpx] tracking-0"
            :class="{ 'text-[#43CF7C] font-bold': currentLetter === letter, 'text-black': currentLetter !== letter }"
          >
            {{
              letter }}
          </text>
        </view>
      </view>
    </view>

    <!-- 长按字母后左侧出现的选择面板（合并版本） -->
    <view v-if="showLetterOptions" class="fixed right-100rpx top-1/3 translate-y-0 transform">
      <!-- 合并后的面板 -->
      <view class="w-100rpx overflow-hidden rounded-10rpx bg-white shadow-lg">
        <!-- 绿色字母头部 -->
        <view class="h-80rpx w-full flex items-center justify-center bg-[#43CF7C]">
          <text class="text-48rpx text-white font-bold">
            {{ currentLetter }}
          </text>
        </view>
        <!-- 下方选项列表 -->
        <view
          v-for="option in letterOptions" :key="option"
          class="h-80rpx w-full flex items-center justify-center hover:bg-gray-100"
          @tap="selectLetterOption(option)"
        >
          <text class="text-32rpx text-[#333]">
            {{ option }}
          </text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import { searcheShouyinMember } from '@/api/member/index';
import { addMaijiaCar } from '@/api/order/index';

// 定义买家接口
interface Buyer {
  id: string;
  name: string;
  phone?: string;
  avatar?: string;
  pinyin?: string;
}

// 返回按钮处理
const goBack = () => {
  uni.navigateBack();
};

// 搜索相关
const searchKeyword = ref('');
const isLoading = ref(false);

const onSearchInput = () => {
  // 输入内容变化时可以进行实时搜索
  // 这里可以添加防抖处理，避免频繁请求
};

const onSearchConfirm = async () => {
  isLoading.value = true;
  try {
    const res = await searcheShouyinMember({
      keywords: searchKeyword.value.trim(),
    });

    if (res.code === 200 && res.data) {
      // 更新索引字母列表
      if (res.data.name_letters && res.data.name_letters.length > 0) {
        indexLetters.value = ['A', 'B', 'C'];
      }

      // 更新买家列表
      if (res.data.memberInfo && res.data.memberInfo.length > 0) {
        const buyers: Buyer[] = res.data.memberInfo.map((item: any) => ({
          id: item.id.toString(),
          name: item.name || item.nickname || item.username,
          phone: item.mobile || item.phone || '',
          avatar: item.img || item.headimgurl || '',
          pinyin: item.letter || '',
        }));

        // 更新买家列表
        buyerList.value = buyers;
      }
      else {
        buyerList.value = [];
      }
    }
  }
  catch (error) {
    console.error('搜索会员失败:', error);
    uni.showToast({
      title: '搜索失败，请重试',
      icon: 'none',
    });
  }
  finally {
    isLoading.value = false;
  }
};

// 字母索引列表
const indexLetters = ref<string[]>(['A', 'B', 'C']);

// 当前选中的字母和显示状态
const currentLetter = ref('');
const scrollIntoId = ref('');

// 字母长按相关状态
const showLetterOptions = ref(false);
const letterOptions = ref<string[]>([]);
let letterOptionsTimer: number | null = null;

// 长按字母处理
const onLetterLongPress = (letter: string) => {
  currentLetter.value = letter;

  // 根据字母生成选项
  generateLetterOptions(letter);

  // 显示选项面板
  showLetterOptions.value = true;

  // 设置3秒后自动关闭
  if (letterOptionsTimer) {
    clearTimeout(letterOptionsTimer);
  }

  letterOptionsTimer = setTimeout(() => {
    showLetterOptions.value = false;
  }, 3000) as unknown as number;

  // 滚动到对应区域
  scrollToLetter(letter);
};

// 根据长按的字母生成选项
const generateLetterOptions = (letter: string) => {
  // 这里可以根据实际需求生成选项
  // 例如：如果是G字母，可以显示"规"、"高"、"管"等
  const optionsMap: Record<string, string[]> = {
    A: ['阿', '安', '爱'],
    B: ['白', '布', '波'],
    C: ['蔡', '曹', '崔'],
    D: ['董', '杜', '邓'],
    E: ['鄂', '恩', '额'],
    F: ['方', '冯', '范'],
    G: ['高', '规', '管'],
    H: ['何', '胡', '韩'],
    I: ['伊', '依', '易'],
    J: ['金', '江', '贾'],
    K: ['柯', '康', '孔'],
    L: ['李', '刘', '林'],
    M: ['马', '孟', '毛'],
    N: ['牛', '聂', '宁'],
    O: ['欧', '偶', '欧阳'],
    P: ['彭', '潘', '庞'],
    Q: ['钱', '秦', '邱'],
    R: ['任', '荣', '饶'],
    S: ['孙', '宋', '史'],
    T: ['唐', '田', '陶'],
    U: ['乌', '万', '韦'],
    V: ['维', '文', '瓦'],
    W: ['王', '吴', '魏'],
    X: ['徐', '许', '夏'],
    Y: ['杨', '袁', '叶'],
    Z: ['张', '赵', '钟'],
    全: ['全部', '常用', '收藏'],
  };

  letterOptions.value = optionsMap[letter] || [];
};

// 选择字母选项
const selectLetterOption = (option: string) => {
  // 将选项内容带入搜索框
  searchKeyword.value = option;

  // 执行搜索
  onSearchConfirm();

  // 关闭选项面板
  showLetterOptions.value = false;
  if (letterOptionsTimer) {
    clearTimeout(letterOptionsTimer);
  }
};

// 滚动到特定字母区域
const scrollToLetter = (letter: string) => {
  scrollIntoId.value = `letter-${letter}`;
};

// 买家数据 - 简化版本显示在图片中的内容
const simpleBuyerList: Buyer[] = [
  { id: '1', name: '临时买家', phone: '18677331337' },
  { id: '2', name: '蔡仔', phone: '18171223705' },
  { id: '3', name: '张三' },
];

// 买家数据 - 完整数据
const buyerList = ref<Buyer[]>([
  { id: '1', name: '临时买家', phone: '18677331337' },
  { id: '2', name: '阿里', phone: '18171223705' },
  { id: '3', name: '张三', phone: '13800138000' },
  { id: '4', name: '李四', phone: '13900139000' },
  { id: '5', name: '王五', phone: '13700137000' },
  { id: '6', name: '赵六', phone: '13600136000' },
  { id: '7', name: '钱七', phone: '13500135000' },
  { id: '8', name: '孙八', phone: '13400134000' },
  { id: '9', name: '周九', phone: '13300133000' },
  { id: '10', name: '吴十', phone: '13200132000' },
  { id: '11', name: '郑十一', phone: '13100131000' },
  { id: '12', name: '冯十二', phone: '13000130000' },
  { id: '13', name: '陈十三', phone: '12900129000' },
  { id: '14', name: '楚十四', phone: '12800128000' },
  { id: '15', name: '魏十五', phone: '12700127000' },
]);

// 过滤后的买家列表
const filteredBuyerList = computed(() => {
  if (!searchKeyword.value.trim()) {
    return buyerList.value.length > 0 ? buyerList.value : simpleBuyerList;
  }

  const keyword = searchKeyword.value.toLowerCase();
  return buyerList.value.filter(buyer =>
    buyer.name.toLowerCase().includes(keyword)
    || (buyer.phone && buyer.phone.includes(keyword)),
  );
});

// 当前选中的买家
const selectedBuyer = ref<Buyer | null>(null);

// 页面参数
const carId = ref<number>(0);

// 处理onLoad生命周期，获取参数
onLoad((options: any) => {
  if (options && options.car_id) {
    carId.value = Number.parseInt(options.car_id) || 0;
    console.log('接收到car_id:', carId.value);
  }
});

// 选择买家
const selectBuyer = (buyer: Buyer) => {
  selectedBuyer.value = buyer;
  // 确保选择买家时关闭字母选项面板
  showLetterOptions.value = false;
  if (letterOptionsTimer) {
    clearTimeout(letterOptionsTimer);
  }

  // 直接调用加入买家接口，不再显示确认弹窗
  addMaijiaCar({
    car_id: carId.value,
    exchangemaijiatype: '',
    maijia_id: buyer.id,
    name: buyer.name,
  }).then((result) => {
    if (result.code === 200) {
      uni.showToast({
        title: '添加成功',
        icon: 'success',
      });

      // 将买家数据返回给购物车页面
      uni.$emit('updateSelectedBuyer', {
        id: result.data.car_id || carId.value,
        maijia_id: buyer.id,
        name: buyer.name,
      });

      // 返回购物车页面
      goBack();
    }
    else {
      uni.showToast({
        title: result.msg || '添加失败',
        icon: 'none',
      });
    }
  }).catch((error) => {
    console.error('添加买家失败:', error);
    uni.showToast({
      title: '添加失败',
      icon: 'none',
    });
  });
};

// 按首字母排序的买家列表
const sortedBuyers = computed(() => {
  const result: Record<string, Buyer[]> = {};

  // 初始化字母分组
  indexLetters.value.forEach((letter) => {
    result[letter] = [];
  });

  // 分组买家
  buyerList.value.forEach((buyer) => {
    // 这里简单处理：使用名字的首字母拼音（实际应用中可能需要拼音转换库）
    const firstLetter = buyer.pinyin
      ? buyer.pinyin.charAt(0).toUpperCase()
      : getFirstLetterInPinyin(buyer.name);

    if (result[firstLetter]) {
      result[firstLetter].push(buyer);
    }
    else {
      // 如果没有匹配的字母分组，放入A组
      result.A.push(buyer);
    }
  });

  // 移除空分组
  Object.keys(result).forEach((key) => {
    if (result[key].length === 0) {
      delete result[key];
    }
  });

  return result;
});

// 简单模拟获取拼音首字母的函数（实际项目中应使用专业拼音库）
const getFirstLetterInPinyin = (name: string) => {
  // 这里使用简单映射，实际应用中应使用专业拼音库
  const firstChar = name.charAt(0);
  const pinyinMap: Record<string, string> = {
    阿: 'A',
    啊: 'A',
    白: 'B',
    包: 'B',
    班: 'B',
    曹: 'C',
    陈: 'C',
    程: 'C',
    蔡: 'C',
    戴: 'D',
    邓: 'D',
    杜: 'D',
    范: 'F',
    方: 'F',
    冯: 'F',
    高: 'G',
    顾: 'G',
    郭: 'G',
    韩: 'H',
    何: 'H',
    胡: 'H',
    金: 'J',
    江: 'J',
    姜: 'J',
    李: 'L',
    刘: 'L',
    梁: 'L',
    马: 'M',
    孟: 'M',
    毛: 'M',
    倪: 'N',
    聂: 'N',
    彭: 'P',
    潘: 'P',
    钱: 'Q',
    秦: 'Q',
    任: 'R',
    荣: 'R',
    孙: 'S',
    宋: 'S',
    史: 'S',
    唐: 'T',
    田: 'T',
    王: 'W',
    吴: 'W',
    魏: 'W',
    徐: 'X',
    许: 'X',
    夏: 'X',
    杨: 'Y',
    袁: 'Y',
    叶: 'Y',
    张: 'Z',
    赵: 'Z',
    钟: 'Z',
    临: 'L',
    时: 'S',
  };

  return pinyinMap[firstChar] || firstChar.toUpperCase();
};

// 点击字母索引
const onLetterClick = (letter: string) => {
  // 判断是否已经选中该字母
  if (currentLetter.value === letter) {
    // 如果已选中，则取消选中，清空搜索值
    currentLetter.value = '';
    searchKeyword.value = '';
    // 关闭选项面板
    showLetterOptions.value = false;
    if (letterOptionsTimer) {
      clearTimeout(letterOptionsTimer);
    }
    // 调用搜索接口获取全部数据
    onSearchConfirm();
  }
  else {
    // 如果未选中，则选中该字母
    currentLetter.value = letter;

    // 如果是"全"字母，展示所有买家
    if (letter === '全') {
      // 清空搜索关键词，显示全部数据
      searchKeyword.value = '';
    }
    else {
      // 将字母带入搜索框
      searchKeyword.value = letter;
    }

    // 执行搜索
    onSearchConfirm();

    // 滚动到对应区域
    scrollToLetter(letter);
  }
};

onMounted(async () => {
  // 加载初始买家数据
  try {
    const res = await searcheShouyinMember({ keywords: '' });

    if (res.code === 200 && res.data) {
      // 更新索引字母列表
      if (res.data.name_letters && res.data.name_letters.length > 0) {
        indexLetters.value = ['A', 'B', 'C'];
      }

      // 更新买家列表
      if (res.data.memberInfo && res.data.memberInfo.length > 0) {
        const buyers: Buyer[] = res.data.memberInfo.map((item: any) => ({
          id: item.id.toString(),
          name: item.name || item.nickname || item.username,
          phone: item.mobile || item.phone || '',
          avatar: item.img || item.headimgurl || '',
          pinyin: item.letter || '',
        }));

        buyerList.value = buyers;
      }
    }
  }
  catch (error) {
    console.error('加载会员数据失败:', error);
  }
});
</script>

<style>
.active-letter {
    background-color: #f5f5f5;
}
</style>
